<template>
  <div class="ai-assistant">
    <!-- 悬浮按钮 -->
    <div class="ai-float-btn" @click="toggleChat" v-show="!showChat">
      <i class="el-icon-service"></i>
      <div class="btn-text">AI助手</div>
    </div>

    <!-- 聊天窗口 -->
    <div class="ai-chat-window" v-show="showChat">
      <!-- 头部 -->
      <div class="chat-header">
        <div class="header-left">
          <i class="el-icon-service"></i>
          <span>教务智能助手</span>
        </div>
        <div class="header-right">
          <el-tooltip content="清空历史" placement="bottom">
            <i class="el-icon-delete" @click="clearHistory"></i>
          </el-tooltip>
          <i class="el-icon-close" @click="toggleChat"></i>
        </div>
      </div>

      <!-- 消息区域 -->
      <div class="chat-messages" ref="messageContainer">
        <!-- 欢迎消息 -->
        <div class="message-item ai-message" v-if="messages.length === 0">
          <div class="message-avatar">
            <i class="el-icon-service"></i>
          </div>
          <div class="message-content">
            <div class="message-text">
              您好！我是教务智能助手 🤖<br/>
              有什么可以帮您的吗？<br/><br/>
              <span style="font-size: 12px; color: #909399;">
                💡 常见问题：<br/>
                • 如何选课？<br/>
                • 如何查看成绩？<br/>
                • 如何提交作业？<br/>
                • 如何查看课表？
              </span>
            </div>
          </div>
        </div>

        <!-- 历史消息 -->
        <template v-for="(msg, index) in messages">
          <!-- 用户消息 -->
          <div :key="'user-' + index" class="message-item user-message">
            <div class="message-content">
              <div class="message-text">{{ msg.userMessage }}</div>
            </div>
            <div class="message-avatar">
              <i class="el-icon-user-solid"></i>
            </div>
          </div>

          <!-- AI回复 -->
          <div :key="'ai-' + index" class="message-item ai-message">
            <div class="message-avatar">
              <i class="el-icon-service"></i>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(msg.aiResponse)"></div>
              <div class="message-time">{{ msg.createTime }}</div>
            </div>
          </div>
        </template>

        <!-- 加载中 -->
        <div class="message-item ai-message" v-if="loading">
          <div class="message-avatar">
            <i class="el-icon-service"></i>
          </div>
          <div class="message-content">
            <div class="message-text typing">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          placeholder="输入您的问题..."
          @keyup.enter.native="sendMessage"
          :disabled="loading"
        >
          <el-button slot="append" icon="el-icon-s-promotion" @click="sendMessage" :loading="loading">
            发送
          </el-button>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AiAssistant',
  data() {
    return {
      showChat: false,
      messages: [],
      inputMessage: '',
      loading: false
    }
  },
  created() {
    // 加载聊天历史
    this.loadHistory()
  },
  methods: {
    toggleChat() {
      this.showChat = !this.showChat
      if (this.showChat) {
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },
    async sendMessage() {
      if (!this.inputMessage.trim() || this.loading) {
        return
      }

      const userMessage = this.inputMessage.trim()
      this.inputMessage = ''
      this.loading = true

      try {
        const res = await this.$request.post('/ai/chat/send', {
          message: userMessage
        })

        if (res.code === '200') {
          // 重新加载历史记录以获取最新消息
          await this.loadHistory()
        } else {
          this.$message.error(res.msg || 'AI服务异常')
          // 即使失败也显示用户消息
          this.messages.push({
            userMessage: userMessage,
            aiResponse: '抱歉，服务暂时不可用，请稍后再试。',
            createTime: new Date().toLocaleString()
          })
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        this.$message.error('发送消息失败，请检查网络连接')
        this.messages.push({
          userMessage: userMessage,
          aiResponse: '网络连接失败，请检查您的网络设置。',
          createTime: new Date().toLocaleString()
        })
      } finally {
        this.loading = false
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },
    async loadHistory() {
      try {
        const res = await this.$request.get('/ai/chat/history', {
          params: { limit: 20 }
        })
        if (res.code === '200') {
          this.messages = res.data || []
        }
      } catch (error) {
        console.error('加载历史失败:', error)
      }
    },
    async clearHistory() {
      this.$confirm('确定要清空所有聊天记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await this.$request.delete('/ai/chat/history/clear')
          if (res.code === '200') {
            this.messages = []
            this.$message.success('清空成功')
          } else {
            this.$message.error(res.msg || '清空失败')
          }
        } catch (error) {
          console.error('清空历史失败:', error)
          this.$message.error('操作失败')
        }
      }).catch(() => {})
    },
    scrollToBottom() {
      const container = this.$refs.messageContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    formatMessage(text) {
      if (!text) return ''
      // 简单的markdown格式化
      return text
        .replace(/\n/g, '<br/>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code>$1</code>')
    }
  }
}
</script>

<style scoped>
.ai-assistant {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 9999;
}

/* 悬浮按钮 */
.ai-float-btn {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  transition: all 0.3s ease;
}

.ai-float-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.6);
}

.ai-float-btn i {
  font-size: 24px;
}

.ai-float-btn .btn-text {
  font-size: 10px;
  margin-top: 2px;
}

/* 聊天窗口 */
.ai-chat-window {
  width: 380px;
  height: 550px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 头部 */
.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: bold;
}

.header-left i {
  font-size: 20px;
}

.header-right {
  display: flex;
  gap: 15px;
}

.header-right i {
  font-size: 18px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.header-right i:hover {
  opacity: 0.8;
}

/* 消息区域 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.ai-message .message-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.user-message .message-avatar {
  background: #409eff;
  color: white;
}

.message-content {
  max-width: 75%;
}

.message-text {
  background: white;
  padding: 10px 14px;
  border-radius: 8px;
  line-height: 1.6;
  word-wrap: break-word;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.user-message {
  flex-direction: row-reverse;
}

.user-message .message-text {
  background: #409eff;
  color: white;
}

.message-time {
  font-size: 11px;
  color: #909399;
  margin-top: 5px;
  padding-left: 5px;
}

/* 输入中动画 */
.typing {
  display: flex;
  gap: 4px;
  padding: 10px 14px;
}

.typing span {
  width: 8px;
  height: 8px;
  background: #909399;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

/* 输入区域 */
.chat-input {
  padding: 15px 20px;
  background: white;
  border-top: 1px solid #ebeef5;
}

.chat-input >>> .el-input-group__append {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
}

.chat-input >>> .el-input-group__append button {
  color: white;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}

/* 代码样式 */
.message-text >>> code {
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  color: #e83e8c;
}

.user-message .message-text >>> code {
  background: rgba(255, 255, 255, 0.2);
  color: white;
}
</style>

